package com.gzyj.jtt808.v2011;

import com.gzyj.jtt808.utils.HexBytesUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.Data;

import java.io.Serializable;

/**
 * @author lhj
 */
@Data
public class PackageHeader implements Serializable {


    private int msgId;//消息ID；
    private HeaderMsgBodyProperty msgBodyProperty;//消息体属性
    private String terminalPhoneNo;//终端手机号
    private short msgNum;//消息流水号

    //消息包封装项
    private short packgeCount;//消息总包数
    private short packageIndex;//报序号 从1开始

    private static short internalMsgNo = 0;

    public PackageHeader() {
    }

    public PackageHeader(int msgId) {
        synchronized ((Short) internalMsgNo) {
            if (internalMsgNo == Short.MAX_VALUE) {
                internalMsgNo = 0;
            }
        }
        this.msgNum = ++internalMsgNo;

        this.msgId = msgId;
    }

    public ByteBuf encode() {
        ByteBuf buf = Unpooled.buffer(16);
        buf.writeShort(this.msgId);
        buf.writeBytes(this.msgBodyProperty.encode());
        buf.writeBytes(HexBytesUtil.WriteBCD(this.terminalPhoneNo, 12));
        buf.writeShort(this.msgNum);
        if (this.msgBodyProperty.isSubcontract()) {
            buf.writeShort(this.packgeCount);
            buf.writeShort(this.packageIndex);

        }

        return buf;

    }

    public PackageHeader decode(ByteBuf buf) {
        byte[] temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgId = Integer.parseInt(HexBytesUtil.bytesToHex(temp), 16);
        temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgBodyProperty = new HeaderMsgBodyProperty();
        this.msgBodyProperty.decode(temp);


        temp = HexBytesUtil.readByOffset(buf, 6);


        this.terminalPhoneNo = HexBytesUtil.ReadBCD(temp, 12);

        temp = HexBytesUtil.readByOffset(buf, 2);
        this.msgNum = Short.parseShort(HexBytesUtil.bytesToHex(temp), 16);

        if (this.msgBodyProperty.isSubcontract()) {
            temp = HexBytesUtil.readByOffset(buf, 2);
            this.packgeCount = Short.parseShort(HexBytesUtil.bytesToHex(temp), 16);
            temp = HexBytesUtil.readByOffset(buf, 2);
            this.packageIndex = Short.parseShort(HexBytesUtil.bytesToHex(temp), 16);
        }


        return this;
    }

}
